package com.chat.service.sym;

import com.chat.dao.UserDao;
import com.chat.util.LockUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class PollingServiceImp implements PollingService {
    private final UserDao userDao;

    @Autowired
    public PollingServiceImp(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Map<String, String> polling(String email) {
        Map<String,String> map=new HashMap<>();

        BlockingDeque<Integer> queue=LockUtil.getMap().get(email);

        /**
         * 我们的并发协议是仅在用户登陆的时候会创建阻塞队列，
         * 如果用户polling而队列为空，则证明用户非法访问，
         * 直接清除所有服务器验证指标，要求用户重新登录。
         */
        if(queue==null){
            map.put("status","-1");
            userDao.clear(email);
            return map;
        }

        Integer integer;

        try {
            //尝试获取队列内容，若成功则返回客户端要求调用相关接口
            integer=queue.poll(25,TimeUnit.SECONDS);
            if(integer==null){
                map.put("status","1");
            }else {
                map.put("status","2");
                map.put("args",integer.toString());
            }
        }catch (Exception ex){
            map.put("status","-1");
        }

        return map;
    }
}
